package com.len.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.len.base.BaseMapper;
import com.len.base.impl.BaseServiceImpl;
import com.len.entity.Node;
import com.len.mapper.NodeMapper;
import com.len.service.NodeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NodeServiceImpl extends BaseServiceImpl<Node,Integer> implements NodeService {

    @Autowired
    NodeMapper nodeDao;

    @Override
    public BaseMapper getMappser() {
        return nodeDao;
    }


    @Override
    public JSONArray getNodeJsonList() {
        List<Node> nodes = selectAll();
        List<Node> supers = nodes.stream().filter( node -> StringUtils.isEmpty(node.getParentId()))
                .collect(Collectors.toList());
        nodes.removeAll(supers);

        supers.sort(Comparator.comparingInt(Node::getOrderNum));
        JSONArray jsonArray = new JSONArray();
        for (Node node : supers) {
            Node child  = child(node,nodes,0);

        }



        return null;
    }

    private Node child(Node node, List<Node> nodes, int i) {
        List<Node> childNode = nodes.stream().filter(s -> s.getParentId().equals(node.getId())).collect(Collectors.toList());
        nodes.removeAll(childNode);
        Node n;
        for (Node node1 : childNode) {
            ++i;
            n  = child(node,nodes,i);
            node.addChild(n);
        }
        return node;
    }


}
